package com.dnjn.mes.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.mes.biz.domain.MesAssembly;
import com.dnjn.mes.biz.domain.MesExcept;
import com.dnjn.mes.biz.domain.MesResolvePlan;
import com.dnjn.mes.biz.domain.MesWorkpiece;
import com.dnjn.mes.biz.enums.DataType;
import com.dnjn.mes.biz.service.IMesAssemblyService;
import com.dnjn.mes.biz.service.IMesExceptService;
import com.dnjn.mes.common.core.controller.BaseController;
import com.dnjn.mes.common.core.domain.AjaxResult;
import com.dnjn.mes.common.core.page.TableDataInfo;
import com.dnjn.mes.common.utils.CountModbusAddrUtil;
import com.dnjn.mes.common.utils.StringUtils;
import com.dnjn.mes.common.utils.poi.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 异常编码表 前端控制器
 * </p>
 *
 * @author Amber
 * @since 2023-07-26
 */
@RestController
@RequestMapping("/biz/mes-except")
public class MesExceptController extends BaseController {

    @Autowired
    protected IMesExceptService baseService;
    @Autowired
    protected IMesAssemblyService assemblyService;

    @PostMapping("/export")
    public void export(HttpServletResponse response, MesExcept domain) {
        List<MesExcept> list = baseService.list(Wrappers.query(domain));
        ExcelUtil<MesExcept> util = new ExcelUtil<MesExcept>(MesExcept.class);
        util.exportExcel(response, list, "参数数据");
    }

    @PostMapping("importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MesExcept> util = new ExcelUtil<MesExcept>(MesExcept.class);
        List<MesExcept> list = util.importExcel(file.getInputStream());
        String message = baseService.importData(list, updateSupport);
        return success(message);
    }

    /**
     * 新增异常
     */
    /*{
        "addrPlc": "MX70.0",
            "exceptMessage": "test",
            "exceptMessageCn": "test",
            "assemblyId": 1693436913643081729
    }*/
   /* @Parameters({
            @Parameter(name = "addrPlc", description = "PLC故障地址"),
            @Parameter(name = "exceptMessage", description = "异常英文"),
            @Parameter(name = "exceptMessageCn", description = "异常中文"),
            @Parameter(name = "equipmentId", description = "ID"),
            //@Parameter(name = "addrModbus", description = "Modbus故障地址"),
            @Parameter(name = "assemblyId", description = "assemblyId")
    })*/
    @Operation(summary = "新增异常")
    @PostMapping("/saveExcept")
    public AjaxResult saveExcept(@Validated @RequestBody MesExcept domain,@RequestHeader( value="equipmentId") long equipmentId) {
        domain.setEquipmentId(equipmentId);
        //domain.setDataType(DataType.BOOL);
            String addrPlc = domain.getAddrPlc();
            //设置modbus地址
            if (Objects.isNull(domain.getAddrModbus())) {
                Integer modbusAddrByPlcAddr = CountModbusAddrUtil.getExceptModbusAddrByPlcAddr(addrPlc);
                domain.setAddrModbus(modbusAddrByPlcAddr);
            }
            //设置模块名称
            MesAssembly mesAssembly = assemblyService.getById(domain.getAssemblyId());
            domain.setAssemblyName(mesAssembly.getAssemblyName());
            //设置datatype
            if (addrPlc.contains(".")) {
                String split = addrPlc.split("\\.")[1];
                int parseInt = Integer.parseInt(split);
                switch (parseInt) {
                    case 0:
                        domain.setDataType(DataType.BIT0);
                        break;
                    case 1:
                        domain.setDataType(DataType.BIT1);
                        break;
                    case 2:
                        domain.setDataType(DataType.BIT2);
                        break;
                    case 3:
                        domain.setDataType(DataType.BIT3);
                        break;
                    case 4:
                        domain.setDataType(DataType.BIT4);
                        break;
                    case 5:
                        domain.setDataType(DataType.BIT5);
                        break;
                    case 6:
                        domain.setDataType(DataType.BIT6);
                        break;
                    case 7:
                        domain.setDataType(DataType.BIT7);
                        break;
                    default:
                        throw new RuntimeException("设置dataType失败，请检查plc地址： " + domain.getAddrPlc());
                }
            }
        domain.setCreateBy(getUsername());
        return toAjax(baseService.save(domain));
    }

    /**
     * 修改异常
     */
    /*@Parameters({
            @Parameter(name = "exceptId", description = "exceptId",required = true),
            @Parameter(name = "addrPlc", description = "PLC故障地址"),
            @Parameter(name = "exceptMessage", description = "异常英文"),
            @Parameter(name = "exceptMessageCn", description = "异常中文"),
    })*/
    @Operation(summary = "修改异常")
    @PutMapping("/editExcept")
    public AjaxResult editExcept(@Validated @RequestBody MesExcept domain) {
        Long exceptId = domain.getExceptId();
        Assert.notNull(exceptId, "exceptId不能为空！");
        String addrPlc = domain.getAddrPlc();
        //设置modbus地址
        if (Objects.isNull(domain.getAddrModbus())) {
            Integer modbusAddrByPlcAddr = CountModbusAddrUtil.getExceptModbusAddrByPlcAddr(addrPlc);
            domain.setAddrModbus(modbusAddrByPlcAddr);
        }
        //设置datatype
        if (addrPlc.contains(".")) {
            String split = addrPlc.split("\\.")[1];
            int parseInt = Integer.parseInt(split);
            switch (parseInt) {
                case 0:
                    domain.setDataType(DataType.BIT0);
                    break;
                case 1:
                    domain.setDataType(DataType.BIT1);
                    break;
                case 2:
                    domain.setDataType(DataType.BIT2);
                    break;
                case 3:
                    domain.setDataType(DataType.BIT3);
                    break;
                case 4:
                    domain.setDataType(DataType.BIT4);
                    break;
                case 5:
                    domain.setDataType(DataType.BIT5);
                    break;
                case 6:
                    domain.setDataType(DataType.BIT6);
                    break;
                case 7:
                    domain.setDataType(DataType.BIT7);
                    break;
                default:
                    throw new RuntimeException("设置dataType失败，请检查plc地址： " + domain.getAddrPlc());
            }
        }
        return toAjax(baseService.updateById(domain));
    }

    /**
     * 获取异常列表,根据模块名称获取
     */
    @Operation(summary = "获取异常列表根据模块id")
    @PostMapping("/getExceptPageByAssemblyId")
    public AjaxResult getExceptPage(@RequestParam(defaultValue = "1") Integer current,
                                    @RequestParam(defaultValue = "10") Integer size, @RequestParam Long assemblyId) {
        Assert.notNull(assemblyId, "assemblyId不能为空！");
        PageHelper.startPage(current, size);
        List<MesExcept> list = baseService.getExceptPageByAssemblyId(assemblyId);
        PageInfo pageInfo = new PageInfo(list);
        return success(pageInfo);
    }


    /**
     * 删除异常
     */
    @Operation(summary = "删除异常")
    @DeleteMapping("/deledtExceptById/{exceptId}")
    public AjaxResult deledtExceptById(@PathVariable("exceptId") Long exceptId) {
        Assert.notNull(exceptId, "exceptId不能为空！");
        //删除异常,关联方案列表信息
        int i = baseService.deledtExceptById(exceptId);
        if(i == 1){
            return success("删除成功");
        }else {
            return error("删除失败");
        }
    }


    /*
     * 根据exceptId获取当前异常下得方案列表
     */
    @Operation(summary = "获取当前异常下得方案列表")
    @PostMapping("/getPlansByExceptId")
    public AjaxResult getExceptPage(@RequestParam Long exceptId, @RequestHeader(value = "equipmentId") long equipmentId) {
        Assert.notNull(exceptId, "exceptId不能为空！");
        List<MesResolvePlan> list = baseService.getPlansByExceptId(exceptId, equipmentId);
        return success(list);
    }


}